<template>
  <el-dialog
    top="10vh"
    width="800px"
    title="添加/编辑"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <SubmitForm
      :rule-form="ruleForm"
      :rules="rules"
      :form-list="formList"
      @change="handleFormChange"
      @save="onSave"
      @close="dialogValue = false"
    >
      <template slot="spec">
        <div style="text-align: right;padding: 10px 0;display: flex;align-items: center;justify-content: space-between">
          <el-radio-group v-model="activeSpec">
            <el-radio-button v-for="item in ruleForm.spec" :key="item.id" :label="item.id">{{ item.name}}</el-radio-button>
          </el-radio-group>
          <div>
            <el-button type="primary" v-if="activeSpec" @click="onEditSpec">编辑规格分组</el-button>
            <el-button type="primary" @click="onAddSpec">添加规格分组</el-button>
            <el-button type="primary" v-if="activeSpec" @click="onDelSpec">删除规格分组</el-button>
          </div>
        </div>

        <el-table ref="childTableRef" :data="ruleForm.spec.find(item => item.id === activeSpec) ? ruleForm.spec.find(item => item.id === activeSpec).children || [] : []">
          <el-table-column label="规格" prop="name">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.price" />
            </template>
          </el-table-column>
          <el-table-column label="企业价格" prop="company_price" >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.company_price" />
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock" >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.stock" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150px">
            <template slot-scope="scope">
              <el-button type="text" @click="onAddRow">添加</el-button>
              <el-button type="text" style="color: #F82222" @click="onDeleteRow(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </SubmitForm>
    <el-dialog
        width="400px"
        title="添加/编辑"
        :visible.sync="dialogValue2"
        :close-on-click-modal="false"
        append-to-body
    >
      <div style="padding-top: 30px">
        <el-form ref="form2Ref" :model="ruleForm2" :rules="rules2" label-width="80px">
          <el-form-item label="规格名称" prop="name">
            <el-input v-model="ruleForm2.name" />
          </el-form-item>
        </el-form>
      </div>
      <slot name="footer">
        <div style="text-align: right;width: 100%;padding-bottom: 20px">
          <el-button type="primary" @click="onSave2">保存</el-button>
          <el-button @click="onClose2">取消</el-button>
        </div>
      </slot>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { http } from '@/api'
const defaultForm = {
  category_id: '',
  name: '',
  image: '',
  spec: [
  ],
  remark: '',
  status: 1
}
export default {
  name: 'FormAdd',
  data() {
    return {
      apiKey: 'foods',
      dialogValue: false,
      activeSpec: '',
      ruleForm: {
        ...defaultForm
      },
      rules: {
        category_id: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        company_price: [
          { required: true, message: '请输入企业价格', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传封面', trigger: 'blur' }
        ],
        spec: [
          {
            // 自定义
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('请添加规格'))
              }  else {
                // 每个规格的名称不能为空
                for (let i = 0; i < value.length; i++) {
                  if (!value[i].name) {
                    callback(new Error('规格名称不能为空'))
                    return
                  }
                  // 每个规格的子规格的名称不能为空
                  for (let j = 0; j < value[i].children.length; j++) {
                    if (!value[i].children[j].name) {
                      callback(new Error('子规格名称不能为空'))
                      return
                    }
                  }
                }
                callback()
              }
            },
          },
        ],
      },
      formList: [
        {
          key: 'category_id',
          name: 'select',
          label: '分类',
          options: [],
          colSpan: 12
        },
        {
          key: 'name',
          name: 'input',
          label: '名称',
          colSpan: 12
        },
        {
          key: 'price',
          name: 'input',
          type: 'number',
          label: '零售起步价格',
          colSpan: 12
        },
        {
          key: 'company_price',
          name: 'input',
          type: 'number',
          label: '企业起步价格',
          colSpan: 12
        },

        {
          key: 'image',
          label: '封面',
          name: 'file',
          colSpan: 12
        },
        {
          key: 'sale_count',
          label: '销量',
          name: 'input',
          colSpan: 12
        },

        {
          label: '规格',
          key: 'spec',
        },
        {
          key: 'desc',
          label: '描述',
          name: 'input',
          type: 'textarea'
        },
        {
          key: 'remark',
          label: '详情',
          name: 'rich',
        },
        {
          key: 'status',
          name: 'switch',
          label: '是否启用',
          activeValue: 1,
          inactiveValue: 0,
          colSpan: 12
        },
      ],
      dialogValue2: false,
      ruleForm2: {
        name: ''
      },
      rules2: {
        name: [
          { required: true, message: '请输入规格名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    http.category.list().then(res => {
      this.formList[0].options = res.data.map(item => {
        return {
          value: item.id,
          name: item.name
        }
      })
    })
  },
  methods: {
    onAddSpec() {
      this.ruleForm2 = {
        name: ''
      }
      this.dialogValue2 = true
    },
    onEditSpec() {
      this.ruleForm2 = {
        ...(this.ruleForm.spec.find(item => item.id === this.activeSpec) || {})
      }
      this.dialogValue2 = true
    },
    onDelSpec() {
      this.$confirm('确定删除该规格分组吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ruleForm.spec = this.ruleForm.spec.filter(item => item.id !== this.activeSpec)
        if (this.ruleForm.spec.length > 0) {
          this.activeSpec = this.ruleForm.spec[0].id
        }
      })
    },
    onSave2() {
      this.$refs.form2Ref.validate(valid => {
        if (valid) {
          if (this.ruleForm2.id) {
            let index = this.ruleForm.spec.findIndex(item => item.id === this.ruleForm2.id)
            this.ruleForm.spec[index] = {
              ...this.ruleForm2
            }
          } else {
            this.ruleForm.spec.push({
              id: new Date().getTime(),
              name: this.ruleForm2.name,
              children: [
                {
                  id: new Date().getTime(),
                  spec: '',
                  price: '',
                  company_price: '',
                  stock: ''
                }
              ]
            })
          }
          if (this.ruleForm.spec.length === 1) {
            this.activeSpec = this.ruleForm.spec[0].id
          }
          this.dialogValue2 = false
        }
      })
    },
    onClose2() {
      this.dialogValue2 = false
    },
    onAddRow() {
      let spec = this.ruleForm.spec.find(item => item.id === this.activeSpec)
      spec.children.push({
        id: new Date().getTime(),
        name: '',
        price: '',
        company_price: '',
        stock: ''
      })
    },
    onDeleteRow(index) {
      let spec = this.ruleForm.spec.find(item => item.id === this.activeSpec)
      spec.children.splice(index, 1)
    },
    handleFormChange({ key, val }) {

    },
    open(row) {
      this.dialogValue = true
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          let spec = []
          if (res.data.spec) {
            spec = JSON.parse(res.data.spec)
          }
          this.ruleForm = {
            ...res.data,
            spec: [
              ...spec
            ]
          }
          console.log(this.ruleForm.spec, '------', spec)
          if (this.ruleForm.spec.length > 0) {
            this.activeSpec = this.ruleForm.spec[0].id
          }
          this.$nextTick(() => {
            this.$refs.childTableRef.doLayout()
          })
        })

      } else {
        this.ruleForm = {
          ...defaultForm,
          spec: [
          ]
        }
        this.$nextTick(() => {
          this.$refs.childTableRef.doLayout()
        })
      }
    },
    onSave() {
      let formData = {
        ...this.ruleForm
      }
      formData.spec = JSON.stringify(formData.spec.map(item => {
        return {
          id: item.id,
          name: item.name,
          children: item.children.map(child => {
            return {
              id: child.id,
              name: child.name,
              price: child.price || 0,
              company_price: child.company_price || 0,
              stock: child.stock || 0
            }
          })
        }
      }))
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, { ...formData }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
